﻿using Fast.DependencyInjection.Dependencies;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Fast.ServiceCollection
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加自动注入服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddAutoInjectedServices(this IServiceCollection services)
        {
            // 获取当前 AppDomain 中加载的所有程序集
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes();

                foreach (var type in types)
                {
                    // 如果类实现了 ITransient 接口
                    if (typeof(ITransient).IsAssignableFrom(type))
                    {
                        // 找到实现了接口的类
                        var interfaces = type.GetInterfaces();
                        foreach (var iface in interfaces)
                        {
                            // 假设接口和实现类的命名一致，例如 IGreeter 对应 Greeter
                            if (iface.Name == $"I{type.Name}")
                            {
                                // 使用 AddTransient 注册
                                services.AddTransient(iface, type);
                            }
                        }
                    }
                }
            }

            return services;
        }


    }
}
